/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "iwdg.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "version.h"
#include "utils.h"
#include "message_queue.h"
#include "ctimer.h"
#include "hw.h"
#include "serial.h"
#include "mstdio.h"
#include "shell.h"
#include "watch_dog.h"
#include "module.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
unsigned int __criticalNesting;
extern unsigned int _eflash; // 来自链接脚本，标示APP Flash的结尾，也即Module Flash的首地址

static Ctimer_t _timer;
static Module_Vector_t _module;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
static void _MsgDeliver(MsgQueue_Msg_t *msg);
static void _ModuleReset(void);
static int APP_Ioctl(unsigned int cmd, va_list args);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static const APP_Vector_t _app =
{
    .vprintf = vprintf,
    .puts    = puts,
    .ioctl   = APP_Ioctl,
    .delay   = HAL_Delay,
};

static void _OnTimerout(int data)
{
    UNUSED(data);

    HW_Toggle(HW_Out_Run);
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
    __criticalNesting = 0;
    uwTickFreq = HAL_TICK_FREQ_1KHZ;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */
#if 0
  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  MX_TIM7_Init();
  MX_IWDG_Init();
  /* USER CODE BEGIN 2 */
#endif
  MsgQueue_Init(_MsgDeliver);
  Ctimer_Init();
  HW_Init();
  Serial_Init();
  MStdio_Init();
  WatchDog_Init();
//  cm_backtrace_init("USB_Camera", "V0.2", _softwareVersion);
  debug("APP:\nVersion: %s\nBuild  : %s\nConfig : %s\n", VERSION, BUILD, CONFIG);
  Shell_Init();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  Ctimer_Start(&_timer, 500, _OnTimerout, 0, 0);
//  Serial_TestCmd(Serial_2, true);
  _ModuleReset();
    while (1)
    {
        MsgQueue_Service();
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
        if(_module.schedule)
        {
            _module.schedule();
        }

        IDLE();
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 180;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Activate the Over-Drive mode
  */
  if (HAL_PWREx_EnableOverDrive() != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/**
 * @brief 处理消息
 * @param msg 消息指针
 */
static void _MsgDeliver(MsgQueue_Msg_t *msg)
{

//    debug("MQ: Dealing msg id: %d\n", msg->id);

    switch(msg->id)
    {
    case MsgQueue_Id_ShellLineIn:
        Shell_OnLine(msg);
        break;

    case MsgQueue_Id_CtimerFire:
        Ctimer_Fire(msg);
        break;

    case MsgQueue_Id_Callback:
    {
        MsgQueue_Callback_t callback;

        memcpy(&callback, msg->data, sizeof(callback));
        callback();
    }
        break;

    case MsgQueue_Id_SerialTest:
        Serial_OnTest(msg);
        break;

//    case MsgQueue_Id_SerialSend:
//        Shell_OnSerialSend(msg);
//        break;

    case MsgQueue_Id_ExtiTest:
        HW_OnExtiMsg(msg);
        break;

    case MsgQueue_Id_WatchDog:
        WatchDog_Reload();
        break;

    case MsgQueue_Id_Printf:
        Mstdio_OnPrintf(msg);
        break;

//    case MsgQueue_Id_Jump:
//        break;

    default:
        debug("Error: Unknown Message, id = %d!\n", msg->id);
        break;
    }
}

static int _ShellCmdReset(void *stream, int argc, char *argv[])
{
    chprintf(stream, "System Reset!\r\n");
    Stream_Flush(stream);
    Utils_DelayMs(5);
//    __disable_fault_irq();
    HAL_NVIC_SystemReset();
    return 0;
}

SHELL_CMD(reset, _ShellCmdReset, "Reset the MCU", "");

static int _ShellCmdVersion(void *stream, int argc, char *argv[])
{
    chprintf(stream, "Version: %s\nBuild : %s\nConfig : %s\n", VERSION, BUILD, CONFIG);
    return 0;
}

SHELL_CMD(version, _ShellCmdVersion, "Show software version", "");

static void _ModuleReset(void)
{
    uint32_t moduleAddr, moduleEStack;
    Module_ResetHandler_t moduleResetHandler;

    moduleAddr = (uint32_t) & _eflash;
    moduleEStack = *(__IO uint32_t*)moduleAddr;
    if((moduleEStack & 0x2FFE0000) != 0x20000000)
    {
        printf("Static module does not exist!\n");
        return;
    }
    else
    {
        debug("Static module loading...\n");
    }

    // module上的中断向量表依然从其flash首地址开始排列，格式也没变。
    // 但Reset_Handler不再是芯片复位后的程序入口，而由APP调用，其原型也已经改变。
    moduleResetHandler = *((Module_ResetHandler_t *) (moduleAddr + 4));
    moduleResetHandler(& _app, & _module);  // 复位module并获取其函数向量表、告知APP的函数向量表
    if((_module.version_major == NULL) || (_module.version_major() != VERSION_MAJOR))
    {
        printf("Static module incompatibility!\n");
        return;
    }

    if(_module.init)
    {
        _module.init(); // 初始化module
    }
}

bool Main_IsModuleLoaded(void)
{
    return (bool)(_module.init != NULL);
}

static int APP_Ioctl(unsigned int cmd, va_list args)
{
    int ret = 0;

    switch(cmd)
    {
    case APP_Cmd_GetSystemClock:
    {
        uint32_t *clk = va_arg(args, uint32_t *);

        *clk = SystemCoreClock;
    }
        break;

    default:
        ret = -1;
    }

    return ret;
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
    while(1)
    {
        HAL_Delay(100);
        HW_Toggle(HW_Out_Run);
    }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
